package com.example.sangong.service.impl;

import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.sangong.dao.SgMenuDao;
import com.example.sangong.entity.SgMenu;
import com.example.sangong.req.menu.MenuListQueryReq;
import com.example.sangong.resp.MenuItemResp;
import com.example.sangong.resp.MenuListResp;
import com.example.sangong.service.SgMenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class SgMenuServiceImpl extends ServiceImpl<SgMenuDao, SgMenu> implements SgMenuService {

    @Resource
    private SgMenuDao sgMenuDao;

    @Override
    public MenuListResp getMenuList(MenuListQueryReq req) {
        MenuListResp resp = new MenuListResp();
        List<MenuItemResp> menuItemRespList = sgMenuDao.selectMenuList(req);
        if(CollectionUtil.isEmpty(menuItemRespList)){
            return resp;
        }
        Map<Long, List<MenuItemResp>> parentIdMap = CollStreamUtil.groupByKey(menuItemRespList, MenuItemResp::getParentId);

        for (MenuItemResp menuItemResp : menuItemRespList) {
            List<MenuItemResp> child = parentIdMap.get(menuItemResp.getId());
            menuItemResp.setChild(child);
        }
        Map<Integer, List<MenuItemResp>> LevelMap = CollStreamUtil.groupByKey(menuItemRespList, MenuItemResp::getLevel);
        //获取顶级level
        List<MenuItemResp> firstLevelList = LevelMap.get(1);
        firstLevelList.sort(Comparator.comparing(MenuItemResp::getOrderNum));
        resp.setMenuList(firstLevelList);
        return resp;
    }
}
